package com.ebocy.hammer.world.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import cn.org.cute.ebocy.config.Param;
import cn.org.cute.ebocy.pf.PlatformFaceServicesImpl;
import cn.org.cute.security.domain.PlatformUser;

import com.ebocy.hammer.core.GameCache;
import com.ebocy.hammer.core.constants.ErrorCode;
import com.ebocy.hammer.core.constants.GameMessageCode;
import com.ebocy.hammer.core.db.AutoIncreaseID;
import com.ebocy.hammer.core.db.DaoManager;
import com.ebocy.hammer.core.db.IDao;
import com.ebocy.hammer.core.domain.Account;
import com.ebocy.hammer.core.domain.GamePlayer;
import com.ebocy.hammer.core.domain.GamePlayerItem;
import com.ebocy.hammer.core.log.EbocyLogManager;
import com.ebocy.hammer.core.message.AbstractS2CMessage;
import com.ebocy.hammer.core.message.S2CErrorCode;
import com.ebocy.hammer.core.service.ItemService;
import com.ebocy.hammer.core.util.ServerAddress;
import com.ebocy.hammer.world.message.C2SPlayerLogin;
import com.ebocy.hammer.world.message.S2CPlayerLogin;
import com.ebocy.hammer.world.resourceManage.ConnectionCount;

/**
 * @author Qingrong Hou
 * 
 *         May 15, 2012
 */
public class WorldService {
	protected static Logger logger = EbocyLogManager.getSystemLogger();
	private static IDao<Account> accountDao = null;
	private static IDao<GamePlayer> gamePlayerDao = null;
	private static ItemService itemService = null;
	private static WorldService worldService = null;

	public static WorldService getInstance() {
		if (worldService == null) {
			worldService = new WorldService();
		}
		return worldService;
	}

	@SuppressWarnings("unchecked")
	private WorldService() {
		if (accountDao == null) {
			accountDao = DaoManager.getInstance().getDao(Account.class);
		}
		if (gamePlayerDao == null) {
			gamePlayerDao = DaoManager.getInstance().getDao(GamePlayer.class);
		}
		if (itemService == null) {
			itemService = ItemService.getInstance();
		}
	}

	/**
	 * 用户登錄
	 */
	public void login(C2SPlayerLogin c2SPlayerLogin, IoSession session) {
		// 获取用户注册信息.
		Account account = getAccount(c2SPlayerLogin);

		// 获取用户游戏信息
		GamePlayer gamePlayer = initGamePlayer(account, c2SPlayerLogin);

		// 添加到在线列表
		ServerAddress serverAddress = ConnectionCount.getGameServerAddress();
		if (serverAddress == null) {
			logger.error("gameServer configuration errors!");
		}

		// 获取消息
		AbstractS2CMessage message = getMessage(account, gamePlayer, serverAddress);

		gamePlayer.setSession(session);

		// 加入緩存
		GameCache.getInstance().addGamePlayer(gamePlayer);

		gamePlayer.sendMessage(message);

	}

	// 根据平台id查找用户平台信息
	private Account getAccount(C2SPlayerLogin c2SPlayerLogin) {
		Account account = null;
		try {
			String platformId = c2SPlayerLogin.getPlatformUserId();
			account = accountDao.findOne(Account.PLATFROMID, platformId);
			if (account == null) {// 未注册用户,初始化用户平台信息
				account = initAccount(c2SPlayerLogin);
			}
		} catch (Exception e) {
			logger.info("根据平台id查找用户平台信息错误#");
		}

		return account;
	}

	// 初始化游戏用户信息
	private GamePlayer initGamePlayer(Account account, C2SPlayerLogin c2sPlayerLogin) {
		GamePlayer gamePlayer = new GamePlayer();
		try {
			if (account != null) {
				gamePlayer = gamePlayerDao.findOne(Account.GAMEPLAYERID, account.getGamePlayerId());
				if (gamePlayer == null) {// 用户游戏信息不存在,创建用户游戏信息
					gamePlayer = GamePlayer.init();
					// 用户游戏id
					long gamePlayerId = AutoIncreaseID.getInstance().getAutoIncreaseID(AutoIncreaseID.GAME_PLAYER_ID);
					gamePlayer.setGamePlayerId(gamePlayerId);
					// 设置用户名
					gamePlayer.setName(account.getName());
					// 设置头像
					gamePlayer.setHeadPortrait(account.getHeadIcon());
					// 初始化用户背包
					gamePlayer = initPlayerItem(gamePlayer);
					// 保存gamePlay信息到db
					gamePlayerDao.insert(gamePlayer);

					// account设置用户游戏id
					account.setGamePlayerId(gamePlayerId);
					accountDao.save(account);
				} else {
					gamePlayer.setKnapsack(itemService.getKnapsack(gamePlayer.getGamePlayerId()));
				}
			}
		} catch (Exception e) {
			logger.info("初始化游戏用户信息错误#");
		}

		return gamePlayer;
	}

	// 用户物品初始化
	private GamePlayer initPlayerItem(GamePlayer gamePlayer) {
		try {
			long gamePlayerId = gamePlayer.getGamePlayerId();
			List<GamePlayerItem> knapsack = new ArrayList<GamePlayerItem>();
			// 过期时间,默认7天,-1为永久有效
			short effectiveTime = 7;
			// 初始化锤子,种类=1
			int hammerId = 1001;
			knapsack.add(itemService.addItem(gamePlayerId, hammerId, 1, (byte) 1, (short) -1, System.currentTimeMillis()));
			gamePlayer.setHammerId(hammerId);
			// 初始化道具,种类=2
			int[] items = { 2026, 2036 };
			// 初始化道具装备位置
			int[] keys = { 1, 2 };
			for (int i = 0; i < items.length; i++) {
				knapsack.add(itemService.addItem(gamePlayerId, items[i], keys[i], (byte) 2, effectiveTime, System.currentTimeMillis()));
			}
			// 初始化物品存入背包
			gamePlayer.setKnapsack(knapsack);
		} catch (Exception e) {
			logger.info("用户物品初始化错误#");
		}

		return gamePlayer;
	}

	// 检查用户平台信息
	private AbstractS2CMessage getMessage(Account account, GamePlayer gamePlayer, ServerAddress gameServer) {
		AbstractS2CMessage message = null;
		if (account == null) {
			message = new S2CErrorCode(ErrorCode.ACCOUNT_INIT_ERROR);
			logger.info("用户平台信息初始化错误#" + ErrorCode.ACCOUNT_INIT_ERROR);
		} else {
			message = new S2CPlayerLogin(gamePlayer, gameServer);
			logger.info("正常登陆#" + GameMessageCode.LOGIN);
		}
		return message;
	}

	// 初始化用户平台信息
	private Account initAccount(C2SPlayerLogin c2SPlayerLogin) {
		Account account = null;
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(Param.ParamName.UID.getName(), c2SPlayerLogin.getPlatformUserId());// 平台ID
		params.put(Param.ParamName.AUTH_TOKEN.getName(), c2SPlayerLogin.getSessionKey());// session_key
		PlatformUser platformUser = PlatformFaceServicesImpl.getInstance().getUserInfo(params);
		// 用户平台信息获取成功
		if (platformUser != null) {
			account = new Account();
			// 平台id
			account.setPlatfromId(platformUser.getPfId());
			// 姓名
			account.setName(platformUser.getPfName());
			// 性别
			account.setGender(platformUser.getPfSex());
			// 头像
			account.setHeadIcon(platformUser.getPfHeadurl());
			// 生日
			account.setBirthDay(platformUser.getPfBirthday());
			// 邮箱
			account.setEmail(platformUser.getPfEmail());
			// 安装时间
			account.setInstallTime();
			// 最后登录时间
			account.setLastLoginTime();
			// 信息更新时间
			account.setUpdateTime();
			// 状态信息
			account.setStatus(platformUser.getPfStatus());
			// 保存account信息到db
			accountDao.insert(account);
		} else {
			account = new Account();
			// 平台id
			account.setPlatfromId(c2SPlayerLogin.getPlatformUserId());
			account.setName(getRandomName());
			account.setHeadIcon("http://img02.taobaocdn.com/sns_logo/i2/T12VRMXeNyXXb1upjX_60x60.jpg");
			account.setGamePlayerId(0);
			// 保存account信息到db
			accountDao.insert(account);
		}
		return account;
	}

	private static String getRandomName() {
		String str = "二款软件请寇家瑞再砍价经济法在陈在且额日雀皮狅";
		Random random = new Random();
		StringBuffer sf = new StringBuffer();
		for (int i = 0; i < 3; i++) {
			int number = random.nextInt(str.length());
			sf.append(str.charAt(number));
		}
		return sf.toString();
	}

	// /**
	// * 退出游戏
	// */
	// public void exitGame(GamePlayer gamePlayer) {
	// if (gamePlayer != null) {
	// // 从缓存中去掉玩家记录
	// GameCache.getInstance().removeGamePlayer(gamePlayer);
	//
	// Room room = GameCache.room4V4Map.get(gamePlayer.getRoomId());
	// if (room != null) {
	// // 通知其他玩家
	// AbstractS2CMessage message = new
	// S2CExitGameMessage(gamePlayer.getGamePlayerId());
	// gamePlayer.sendMessageToRoomOther(message);
	//
	// // 从房间中退出
	// room.members.remove(gamePlayer.getGamePlayerId());
	// }
	// }
	// }
}
